/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *removeNodes(ListNode *head)
    {
        vector<int> list;
        ListNode *node = head;
        while (node != nullptr)
        {
            list.push_back(node->val);
            node = node->next;
        }
        int n = list.size();
        int rightMax = list[n - 1];
        for (int i = n - 2; i >= 0; --i)
        {
            rightMax = max(rightMax, list[i]);
            if (list[i] < rightMax)
            {
                list[i] = -1;
            }
        }
        ListNode newHead;
        node = &newHead;
        for (int i = 0; i < n; ++i)
        {
            if (list[i] != -1)
            {
                node->next = new ListNode(list[i]);
                node = node->next;
            }
        }
        return newHead.next;
    }
};